<script setup>
import axios from 'axios';
import {onMounted, ref} from 'vue';
const apiBaseUrl = import.meta.env.VITE_API_BASE_URL;  // 从环境变量获取基础 URL

const formState = ref({
  air_condition_num: 10,
  default_mode: 'cold',
  default_highest_temp: 30,
  default_lowest_temp: 18,
  default_tar_temp: 26,
  default_wind_level: 1,
  high_fee_rate: 1.5,
  middle_fee_rate: 1.0,
  low_fee_rate: 0.5
});

// 定义状态和表单状态的响应式数据
const currentConfig = ref({
  air_condition_num: 0,
  default_mode: 'cold',
  default_highest_temp: 25,
  default_lowest_temp: 18,
  default_tar_temp: 22,
  default_wind_level: 1,
  high_fee_rate: 1.5,
  middle_fee_rate: 1.0,
  low_fee_rate: 0.5,
  is_running: false
});


// 获取总机状态的函数
const fetchCenterState = async () => {
  try {
    const response = await axios.get(`${apiBaseUrl}/admin/center/get_center_state`);
    currentConfig.value = response.data;

    console.log("空调资源：",response.data.air_condition_num)
    localStorage.setItem('currentConfig', JSON.stringify({
      currentConfig:currentConfig.value
    }));

    console.log('总机状态更新成功:', response.data);
  } catch (error) {
    console.error('获取总机状态失败:', error);
    alert('无法连接到中央空调！');
  }
};

// 提交表单的函数
const handleSubmit = async () => {
  try {
    console.log(formState.value)
    const response = await axios.post(`${apiBaseUrl}/admin/center/modify`, formState.value);
    if(response.data.status){
      alert("提交成功！")
      await fetchCenterState();  // 提交后重新获取最新状态
    }else {
      alert("提交失败：",response.data.message)
    }

  } catch (error) {
    console.error('提交失败:', error);
    alert('无法连接');
  }
};

// 挂载时获取总机状态
onMounted(() => {
  fetchCenterState();
});


// 开机或关机
const toggleSystem = async () => {
  const endpoint = currentConfig.value.is_running ? '/admin/center/close' : '/admin/center/open';
  try {
    const response = await axios.post(`${apiBaseUrl}${endpoint}`);
    alert(`系统${currentConfig.value.is_running ? '关闭' : '启动'}: 成功`);
    await fetchCenterState();
  } catch (error) {
    console.error(`系统${currentConfig.value.is_running ? '关闭' : '启动'}失败:`, error);
    alert(`系统${currentConfig.value.is_running ? '关闭' : '启动'}失败`);
    await fetchCenterState();
  }
};

</script>


<template>
  <div class="base">
    <div class="panel">
      <form class="config-form" @submit.prevent="handleSubmit">
      <div class="form-content">

          <div class="left-container">
            <!-- 左侧表单项 -->
            <div class="item">
              <label for="max-ac">最大可运行空调数量：</label>
              <input id="max-ac" type="text" v-model="formState.air_condition_num">
            </div>
            <div class="item">
              <label>工作模式：</label>
              <input v-model="formState.default_mode" type="radio" id="mode-cool" name="mode" value="cold" checked><label for="mode-cool">制冷</label>
              <input v-model="formState.default_mode" type="radio" id="mode-heat" name="mode" value="hot"><label for="mode-heat">制热</label>
            </div>
            <div class="item">
              <label for="temp-upper">温度上限：</label>
              <input id="temp-upper" type="text" v-model="formState.default_highest_temp">
            </div>
            <div class="item">
              <label for="temp-lower">温度下限：</label>
              <input id="temp-lower" type="text" v-model="formState.default_lowest_temp">
            </div>
          </div>
          <div class="right-container">
            <!-- 右侧表单项 -->
            <div class="item">
              <label for="rate-low">低档费率：</label>
              <input id="rate-low" type="text" v-model="formState.low_fee_rate"> 元 / 度
            </div>
            <div class="item">
              <label for="rate-mid">中档费率：</label>
              <input id="rate-mid" type="text" v-model="formState.middle_fee_rate"> 元 / 度
            </div>
            <div class="item">
              <label for="rate-high">高档费率：</label>
              <input id="rate-high" type="text" v-model="formState.high_fee_rate"> 元 / 度
            </div>
            <div class="item">
              <label for="default-temp">默认温度：</label>
              <input id="default-temp" type="text" v-model="formState.default_tar_temp">
            </div>
            <div class="item">
              <label>默认风速：</label>
              <input value="1" type="radio" name="fan-speed" checked v-model="formState.default_wind_level"><label>低档</label>
              <input value="2" type="radio" name="fan-speed" v-model="formState.default_wind_level"><label>中档</label>
              <input value="3" type="radio" name="fan-speed" v-model="formState.default_wind_level"><label> 高档</label>
            </div>
          <button type="submit" class="submit-button">提交</button>
        </div>

      </div>
      </form>
    </div>
    <div class="details">
      <div class="details-content">
        <div class="details-info">
          <h2 style="text-align: center;margin-bottom: 5px">当前中央空调总机设置</h2>
          <h4 style="text-align: center; margin-bottom: 10px"
              :style="{ color: currentConfig.is_running ? 'red' : 'grey' }">
            {{ currentConfig.is_running ? '运行中' : '未运行' }}
          </h4>

          <div class="item">
            最大可运行空调数量：{{ currentConfig.air_condition_num }}
          </div>
          <div class="item">
            工作模式：{{ currentConfig.default_mode }}
          </div>
          <div class="item">
            温度区间：{{ currentConfig.default_lowest_temp }}° ~ {{ currentConfig.default_highest_temp }}°
          </div>
          <div class="item">
            默认温度：{{ currentConfig.default_tar_temp }}°
          </div>
          <div class="item">
            默认风速：{{ currentConfig.default_wind_level }}
          </div>
          <div class="item">
            费率：{{ currentConfig.low_fee_rate }}（低） {{ currentConfig.middle_fee_rate }}（中） {{ currentConfig.high_fee_rate }}（高）
          </div>

        </div>
        <button @click="toggleSystem" class="submit-button">
          {{ currentConfig.is_running ? '关机' : '开机' }}
        </button>
      </div>
    </div>
  </div>

</template>

<style scoped>
.panel {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 20px;
  position: fixed;
  top: 64px;
  left: 0;
  right: 400px;
  bottom: 10px;
}
.details {
  display: flex;
  padding: 10px 20px;
  justify-content: space-between;
  align-items: center;
  float: right;
  width: 410px;
  position: fixed;
  top: 64px;
  right: 10px;
  bottom: 10px;
}

.details-content{
  width: 100%; /* 使表单宽度根据父容器调整 */
  padding: 30px;
  background-color: white;
  box-shadow: 0 4px 8px rgba(0,0,0,0.1);
  border-radius: 8px;
  height: 100%;
}

input[type="text"]{
  width: 100px;
  height: 25px;
  background-color: white;
  border-radius:10px;
  border:1px solid dodgerblue;
  margin: 10px;
  color:black;
}
input[type="radio"]{
  width: 20px;
  margin: 10px;
  align-self: center;
}

.config-form {
  width: 100%; /* 使表单宽度根据父容器调整 */
  padding: 20px;
  box-shadow: 0 4px 8px rgba(0,0,0,0.1);
  border-radius: 8px;
  height: 100%;
}

.form-content {
  display: flex;
  width: 100%;
  height: 100%;
  align-items: stretch;
}

.left-container, .right-container {
  flex: 1;
  padding: 10px;
  align-items: stretch;

}
.item{
  margin-bottom: 20px;
}
.submit-button {
  padding: 20px 40px;
  background-color: #007BFF;
  color: white;
  border: none;
  border-radius: 5px;
  cursor: pointer;
  transition: background-color 0.3s ease;

  position:absolute;
  right:40px;
  bottom:30px;
}

.submit-button:hover {
  background-color: #0056b3;
}
</style>
